package com.jjc.MyWebApp.Routes;

import com.jfinal.config.Routes;
import com.jfinal.kit.StrKit;
import com.jfinal.log.Log;
import com.jjc.MyWebApp.Annotation.Controller;
import com.jjc.MyWebApp.kit.ClassScanKit;

import java.util.Set;

/**
 * Created by jiaji on 2017/4/26.
 */
public class RoutesScan extends Routes {
    private static final Log log = Log.getLog(RoutesScan.class);

    public void config() {
        setBaseViewPath("/view");

        // 查询所有继承BaseController的子类
        Set<Class<?>> controllerClasses = ClassScanKit.searchByClassLoader(BaseController.class);

        for (Class controller : controllerClasses) {
            Controller ControllerInfo = (Controller) controller.getAnnotation(Controller.class);
            if (ControllerInfo == null) {
                if (log.isWarnEnabled())
                    log.warn(controller.getName() + "继承了BaseController，但是没有注解绑定映射路径，请检查是否已经手动绑定 ！！！");
                throw new RuntimeException(controller.getName() + "继承了BaseController，但是没有注解绑定映射路径，请检查是否已经手动绑定 ！！！");
            }
            String[] Controllerkeys = ControllerInfo.value();
            String ControllerViewPath = ControllerInfo.viewPath();
            for (String Controllerkey : Controllerkeys) {
                Controllerkey = Controllerkey.trim();
                if (Controllerkey.equals("")) {
                    if (log.isErrorEnabled()) log.error(controller.getName() + "注解错误，映射路径为空");
                    throw new RuntimeException(controller.getName() + "注解错误，映射路径为空");
                }
                // 注册映射
                if(StrKit.notBlank(ControllerViewPath)){
                    add(Controllerkey, controller, ControllerViewPath);
                }else{
                    add(Controllerkey, controller);
                }
                if (log.isDebugEnabled())
                    log.debug("注册Controller: controller = " + controller.getName() + ", " + Controllerkey);

            }
        }
    }
}
